package com.tea.room.model.xmlBean;

import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;

/**
 * xml转map
 * 
 * @ClassName:Xml2Map
 * @Description:TODO()
 * @date:2019年4月9日 下午5:15:22
 * @author ShiP
 */
public class Xml2Map {

    /**
     * @Title: xmlToMap
     * @param: req
     * @return: Map<String,String>
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> xmlToMap(HttpServletRequest req) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader saxReader = new SAXReader();
        ServletInputStream inputStream = req.getInputStream();
        Document document = saxReader.read(inputStream);
        Element element = document.getRootElement();
        List<Element> list = element.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        inputStream.close();
        return map;
    }

    /**
     * 对象转xml 
     * @Title: beanToXml 
     * @return: String 
     */
    public static String beanToXml(Message msg) {
        XStream xStream = new XStream();
        xStream.alias("xml", msg.getClass());
        return xStream.toXML(msg);
    }

    /**
     * XML字符串转化为map
     * @param xml
     * @return map
     * @throws Exception 
     */
    public static Map<String, String> xmlToMap(String xml) throws Exception{
        Map<String, String> map = new HashMap<String, String>();
        Document document =  DocumentHelper.parseText(xml);        
        Element element = document.getRootElement();
        List<Element> list = element.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        return map;
    }

}
